﻿using BO;
using BO.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Dynamic;
using WebUI3;
using System.Web.Script.Serialization;
namespace WebUI3.Controllers
{
    public class CompanyController : BaseController
    {
        public ViewResult Index()
        {
            return View();
        }
        public JsonResult GetList()
        {
            var list = ListFactory<CompanyList>.GetList("");          
            Session.Add("CompanyList", list);
            return Json(list.ToModel());
        }
        public JsonResult SaveList()
        {
            string deleted = Request.Form["deleted"];
            string inserted = Request.Form["inserted"];
            string updated = Request.Form["updated"];
            var jsObj = new JavaScriptSerializer();
            var list = Session["CompanyList"] as CompanyList;
            if (list == null)
                throw new Exception("Session 不匹配");
            if (deleted != null)
            {
                //把json字符串转换成对象
               var listDeleted = jsObj.Deserialize<List<Company>>(deleted);
                //TODO 下面就可以根据转换后的对象进行相应的操作了
               foreach (var obj in listDeleted)
               {
                   list.RemoveByOID(obj.ID);
                  // Company.Delete(obj.ID);                
               }
            }

            if (inserted != null)
            {
                //把json字符串转换成对象
               var listInserted = jsObj.Deserialize<List<Company>>(inserted);
                foreach (var obj in listInserted)
                {
                    list.Add(obj);
                   // obj.Save();
                }
            }

            if (updated != null)
            {
                //把json字符串转换成对象
                var listUpdated = jsObj.Deserialize<List<Company>>(updated);
                foreach (var obj in listUpdated)
                {
                    var lObj = list.GetByOID(obj.ID);
                    lObj.UpdateObject(obj);
                }
            }
            list.Save();
            return Json("Success");
        }
     
    }
}
